import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Icon, Modal, Form, Input, Select, Upload } from 'antd';
//@ts-ignore
import LzEditor from 'react-lz-editor';
import Service from '@/public/http/services';
import style from './index.css';
const { TextArea } = Input;
const { Option } = Select;
const CreateModal: React.FC<any> = ({ formData,interlist, visible, title, onOK, onCancel, form, dispatch }) => {
    const [defaultContent, setDefaultContent] = useState('<h3>请输入</h3>');
    useEffect(() => {
        if(visible) {
            setDefaultContent(formData.summary || '<h3>请输入</h3>');
            if (formData && Object.keys(formData).length) {
                setCurCoverImg([{ uid: formData.id, url: formData.coverImg }] as any);
                setCurAuthorPortraitImg([{ uid: formData.id, url: formData.authorPortrait }] as any);
                setCurUrlImg([{ uid: formData.id, url: formData.url }] as any);
                setAihaolist(formData.tags as any)
            }
        }
    }, [visible, formData])

    const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    }

    const { getFieldDecorator } = form;
    const [loading, setLoading] = useState(false);

    const [curCoverImg, setCurCoverImg] = useState([]);
    const [aihaolist,setAihaolist] = useState("");

    const coverUploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurCoverImg([{
            uid,
            name,
            url: curCoverFileUrl,
        }] as any);
    }

    const coverHandleChange = (file) => { }

    const [curCoverActionUrl, setCurCoverActionUrl] = useState();
    const [curCoverUploadData, setCurCoverUploadData] = useState({});
    const [curCoverFileUrl, setCurCoverFileUrl] = useState('');
    const coverBeforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurCoverActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurCoverFileUrl(host + '/' + key)
        setCurCoverUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status : '200',
            signature
        });
        return true;
    }

    const coverRemoveSuccess = () => {
        setCurCoverImg([] as any);
    }

    /**
     * @desc
     */
    const upload: any = {
        name: 'file',
        action: curCoverActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        onSuccess: coverUploadSuccess,
        onChange: coverHandleChange,
        beforeUpload: coverBeforeUpload,
        onRemove: coverRemoveSuccess,
        data: curCoverUploadData
    }


    /**
     * author
     */
    const [curAuthorPortraitImg, setCurAuthorPortraitImg] = useState([]);

    const authorPortraitUploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurAuthorPortraitImg([{
            uid,
            name,
            url: curAuthorPortraitFileUrl,
        }] as any);
    }

    const authorPortraitHandleChange = (file) => { }

    const [curAuthorPortraitActionUrl, setCurAuthorPortraitActionUrl] = useState();
    const [curAuthorPortraitUploadData, setCurAuthorPortraitUploadData] = useState({});
    const [curAuthorPortraitFileUrl, setCurAuthorPortraitFileUrl] = useState('');
    const authorPortraitBeforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurAuthorPortraitActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurAuthorPortraitFileUrl(host + '/' + key)
        setCurAuthorPortraitUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status : '200',
            signature
        });
        return true;
    }

    const authorPortraitRemoveSuccess = () => {
        setCurAuthorPortraitImg([] as any);
    }

    const authorPortraotUpload: any = {
        name: 'file',
        action: curAuthorPortraitActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        onSuccess: authorPortraitUploadSuccess,
        onChange: authorPortraitHandleChange,
        beforeUpload: authorPortraitBeforeUpload,
        onRemove: authorPortraitRemoveSuccess,
        data: curAuthorPortraitUploadData
    }

    /**
     * 资料文件
     */
    const [curUrlImg, setCurUrlImg] = useState([]);

    const urlUploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurUrlImg([{
            uid,
            name,
            url: curUrlFileUrl,
        }] as any);
    }

    const urlHandleChange = (file) => { }

    const [curUrlActionUrl, setCurUrlActionUrl] = useState();
    const [curUrlUploadData, setCurUrlUploadData] = useState({});
    const [curUrlFileUrl, setCurUrlFileUrl] = useState('');
    const urlBeforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurUrlActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurUrlFileUrl(host + '/' + key)
        setCurUrlUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status : '200',
            signature
        });
        return true;
    }

    const urlRemoveSuccess = () => {
        setCurUrlImg([] as any);
    }

    const urlUpload: any = {
        name: 'file',
        action: curUrlActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        onSuccess: urlUploadSuccess,
        onChange: urlHandleChange,
        beforeUpload: urlBeforeUpload,
        onRemove: urlRemoveSuccess,
        data: curUrlUploadData
    }


    /**
     * editor config
     */
    const [curEditorList, setCurEditorList] = useState([])
    const [htmlContent, setHtmlContent] = useState('');

    const receiveHtml = (content: string) => {
        setHtmlContent(content);
        setCurEditorList([]);
    }

    const handleEditorFileChange = (changedValue) => {
        let { file, fileList } = changedValue;
        for (const item of curEditorList) {
            if ((item as any).uid === file.uid) return;
        }
        const { uid, name } = file;
        setCurEditorList(curEditorList.concat([{
            uid,
            name,
            url: curEditorUrl,
        }] as any));
    }

    const [curEditorActionUrl, setCurEditorActionUrl] = useState();
    const [curEditorUploadData, setCurEditorUploadData] = useState({});
    const [curEditorUrl, setCurEditorUrl] = useState('');
    const editorBeforeUpload = async (file, fileList) => {
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurEditorActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurEditorUrl(host + '/' + key)
        setCurEditorUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeEditorSuccess = (file) => {
        let list = [];
        for (const item of curEditorList) {
            if ((item as any).uid !== file.uid) list.push(item);
        }
        setCurEditorList(list);
    }

    const selectinter = (item)=>{
      var temp = aihaolist
      if(temp && temp.indexOf(item) >  -1){
        temp = temp.replace(item+',',"");
      }else{
        if(!temp){
          temp = ""
        }
        temp += item+','
      }
      setAihaolist(temp)
      form.tags = temp
    }

    const editorUpload = {
        action: curEditorActionUrl,
        onChange: handleEditorFileChange,
        listType: 'picture',
        data: curEditorUploadData,
        multiple: false,
        beforeUpload: editorBeforeUpload,
        onRemove: removeEditorSuccess,
    }

    return (
        <Modal
            visible={visible}
            title={title}
            okText={'保存'}
            cancelText={'取消'}
            onOk={() => {
                setCurCoverImg([])
                setCurAuthorPortraitImg([])
                setCurEditorList([])
                setCurUrlImg([])
                setAihaolist("")
                onOK && onOK(form, {
                    authorPortraits: curAuthorPortraitImg,
                    urls: curUrlImg,
                    coverImgs: curCoverImg,
                    summary: htmlContent
                })
            }}
            onCancel={() => {
                setCurCoverImg([])
                setCurAuthorPortraitImg([])
                setCurUrlImg([])
                setAihaolist("")
                onCancel(form)
            }}
            width={'65%'}
        >
            <Form.Item {...formItemLayout} label={'资料名称'}>
                {
                    getFieldDecorator('name', {
                        initialValue: formData.name,
                        rules: [{ required: true, message: '请输入资料名称' }],
                    })(<Input className={style.w220} placeholder={'请输入资料名称'} />)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'是否Vip'}>
              {
                getFieldDecorator('isVip', {
                  initialValue: formData.isVip,
                  rules: [{ required: true, message: '请选择vip' }],
                })(<Select className={style.w220} placeholder={'请选择vip'}>
                  <Option value={1}>是</Option>
                  <Option value={0}>不是</Option>
                </Select>)
              }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'资料封面'}>
                {
                    getFieldDecorator('coverImg', {
                        initialValue: curCoverImg.length ? (curCoverImg[0] as any).url : '',
                        rules: [{ required: true, message: '请上传封面' }],
                        getValueFromEvent: (e) => {
                            return e.fileList
                        }
                    })(<Upload
                        className={style['upload-btn']}
                        {...upload}
                        fileList={curCoverImg}
                    >
                        <div key={'upload-btn'}>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'资料作者'}>
                {
                    getFieldDecorator('author', {
                        initialValue: formData.author,
                        rules: [{ required: true, message: '请输入资料作者' }],
                    })(<Input className={style.w220} placeholder={'请输入资料作者'} />)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'作者头像'}>
                {
                    getFieldDecorator('authorPortrait', {
                        initialValue: curAuthorPortraitImg.length ? (curAuthorPortraitImg[0] as any).url : '',
                        rules: [{ required: true, message: '请上传作者头像' }],
                        getValueFromEvent: (e) => {
                            return e.fileList
                        }
                    })(<Upload
                        className={style['upload-btn']}
                        {...authorPortraotUpload}
                        fileList={curAuthorPortraitImg}
                    >
                        <div key={'upload-btn'}>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'资料类型'}>
                {
                    getFieldDecorator('type', {
                        initialValue: formData.type,
                        rules: [{ required: true, message: '请选择资料类型' }],
                    })(<Select className={style.w220} placeholder={'请选择资料类型'}>
                        <Option value={1}>图片</Option>
                        <Option value={2}>WORD文档</Option>
                        <Option value={3}>PPT文档</Option>
                        <Option value={4}>PDF文档</Option>
                        <Option value={5}>视频文档</Option>
                        <Option value={6}>音频文档</Option>
                        <Option value={7}>EXCEL文档</Option>
                    </Select>)
                }
            </Form.Item>

            <Form.Item {...formItemLayout} label={'上传资料'}>
                {
                    getFieldDecorator('url', {
                        initialValue: curUrlImg.length ? (curUrlImg[0] as any).url : '',
                        rules: [{ required: true, message: '请上传资料' }],
                        getValueFromEvent: (e) => {
                            return e.fileList
                        }
                    })(<Upload
                        className={style['upload-btn']}
                        {...urlUpload}
                        fileList={curUrlImg}
                    >
                        <div key={'upload-btn'}>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>

            <Form.Item label='资料介绍' {...formItemLayout}>
                {getFieldDecorator('summary', {
                    // rules: [{ required: true, message: '请编辑内容' }],
                })(
                    <LzEditor
                        active={true}
                        importContent={defaultContent}
                        cbReceiver={receiveHtml}
                        uploadProps={{ ...editorUpload, fileList: curEditorList }}
                        video={false}
                        audio={false}
                        lang={'ch'}
                    />
                )}
            </Form.Item>
            <Form.Item {...formItemLayout} label={'关键词'}>
                {
                    getFieldDecorator('keywords', {
                        initialValue: formData.keywords,
                    })(<Input placeholder={'请输入搜索关键词并以“，”隔开。'} />)
                }
            </Form.Item>
        </Modal>
    );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(CreateModal);
export default connect((state: any) => {
    return {
    }
})(WrappedCreateModal);
